#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
import sys


def formatLine(line):
    splitline = line.split("\t")
    JrId = int(splitline[0])
    FullTitle = splitline[1]
    MedAbbr = splitline[2]
    pISSN = splitline[3]
    eISSN = splitline[4]
    ISOAbbr = splitline[5]
    NlmId = splitline[6]

    current_record = {}
    current_record["JrId"] = JrId
    # temp = {}

    if FullTitle != "":
        current_record["FullTitle"] = [FullTitle]
        # current_record["FullTitleAlias"] = [FullTitle]
    if MedAbbr != "":
        current_record["MedAbbr"] = [MedAbbr]
        # temp[MedAbbr] = 0
    if pISSN != "":
        current_record["pISSN"] = pISSN
    if eISSN != "":
        current_record["eISSN"] = eISSN
    if ISOAbbr != "":
        current_record["ISOAbbr"] = [ISOAbbr]
        # temp[ISOAbbr] = 0
    if NlmId != "":
        current_record["NlmId"] = NlmId
    # if len(temp) != 0:
    #     current_record["AbbrAlias"] = []
    #     for key in temp.keys():
    #         current_record["AbbrAlias"].append(key)

    return current_record


if __name__ == "__main__":
    DB_NAME = "journal"
    COLLECTION_NAME = "journal"

    connection = MongoClient('localhost', 27017)
    db = connection[DB_NAME]
    collection = db[COLLECTION_NAME]

    count = 0
    records = []
    infile = open(sys.argv[1], 'r')
    infile.readline()
    for line in infile:
        line = line.rstrip()
        current_record = formatLine(line)
        records.append(current_record)
        count += 1
        if count == 1000:
            collection.insert_many(records)
            del records[:]
            count = 0
    infile.close()
    if count != 0:
        collection.insert_many(records)
    connection.close()
